import { Injectable } from '@nestjs/common';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { UserEntity } from './entities/user.entity';
import { Repository } from 'typeorm';
import { BusinessException } from 'src/common/filter/business-exception/business.exception';

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(UserEntity)
    private userRepository: Repository<UserEntity>,
  ) {}
  async create(createUserDto: CreateUserDto) {
    const { username } = createUserDto;
    const existUser = await this.userRepository.findOne({
      where: { username },
    });
    if (existUser) {
      throw new BusinessException('用户名已存在');
    }
    const newUser = this.userRepository.create(createUserDto);
    return await this.userRepository.save(newUser);
    // return 'This action adds a new user';
  }

  async findAll() {
    return await this.userRepository.find();
    // return `This action returns all user`;
  }

  findOne(id: string) {
    return this.userRepository.findOne({ where: { id } });
    // return `This action returns a #${id} user`;
  }

  async findOneByUsername(username: string) {
    return await this.userRepository.findOne({ where: { username } });
  }
  // 修改昵称
  async updateInfo(id: string, updateUserDto: UpdateUserDto, user: UserEntity) {
    const updateUser = await this.userRepository.findOne({
      where: { id: user.id },
    });
    if (!updateUser) throw new BusinessException('未找到用户');
    if (updateUserDto.name) updateUser.name = updateUserDto.name;

    return await this.userRepository.save(updateUser);
  }

  // 修改密码
  async updatePassword(
    id: string,
    updateUserDto: UpdateUserDto,
    user: UserEntity,
  ) {
    const updateUser = await this.userRepository.findOne({
      where: { id: user.id },
    });
    if (!updateUser) throw new BusinessException('未找到用户');
    if (
      !updateUserDto.check_password ||
      updateUserDto.check_password !== updateUser.password
    )
      throw new BusinessException('密码校验失败');

    if (updateUserDto.password) updateUser.password = updateUserDto.password;
  }

  remove(id: number) {
    return `This action removes a #${id} user`;
  }
}
